<?php
/**
 * 家政模型
 */
namespace Common\Model;

class HouseWorkModel extends BaseModel{

    const MAX_ORDERS_PER_INTERVAL=1;//最时段最大允许报名数

    const STATUS_ONLINE     = 1;//上线
    const STATUS_OFFLINE    = 0;

    const ORDER_STATUS_INIT         = 1;
    const ORDER_STATUS_CANCEL       = 2;
    const ORDER_STATUS_ASSIGN       = 3;
    const ORDER_STATUS_COMPLETE     = 4;

    public static function getOrderStatusKv(){
        return [
            self::ORDER_STATUS_INIT     => '待接单',//初始状态
            self::ORDER_STATUS_CANCEL   => '已取消',
            self::ORDER_STATUS_ASSIGN   => '已派单',
            self::ORDER_STATUS_COMPLETE => '已完成',
        ];
    }


    /**
     * @param $itemId
     * @param $date
     * @return array
     */
    public static function getIntervalStatus($itemId,$date){
        $times=self::getWorkHour();
        $data=[];
        foreach($times as $hour){
            $data[]=[$hour,self::getTimeOrder($itemId,$date,$hour)?1:0];
        }
        return $data;
    }


    private static function getKey($itemId,$date,$hour){
        return md5($itemId.'_'.$date.$hour);
    }
    public static function getTimeOrder($itemId,$date,$hour){
        $key=self::getKey($itemId,$date,$hour);
        $num=intval(S($key));
        if ($num<self::MAX_ORDERS_PER_INTERVAL){
            return true;
        }
        return false;
    }

    public static function timeOrderReduce($itemId,$date,$hour){
        $key=self::getKey($itemId,$date,$hour);
        $num=intval(S($key));
        if ($num>0){
            S($key,$num-1);
        }
    }
    public static function timeOrderPlus($itemId,$date,$hour){
        $key=self::getKey($itemId,$date,$hour);
        $num=intval(S($key));
        S($key,$num+1);
    }



    private static function getItemPicKv(){
        return self::getItemInstance()->getField('id,imgList',true);
    }

    public static function getItemKv(){
        return self::getItemInstance()->getField('id,title',true);
    }
    public static function getEnableItemKv(){
        $status=self::STATUS_ONLINE;
        $now=time();
        return self::getItemInstance()->where("status={$status} and beginShowTime<{$now}")->getField('id,title',true);
    }

    private static $eventInstance=null;
    public static function getItemInstance(){
        if(!self::$eventInstance){
            self::$eventInstance=M('housework_item',null,DB_MAIN_CFG);
        }
        return self::$eventInstance;
    }

    private static $joinInstance=null;
    public static function getOrderInstance(){
        if(!self::$joinInstance){
            self::$joinInstance=M('housework_order',null,DB_MAIN_CFG);
        }
        return self::$joinInstance;
    }


    /**
     * 工作时间
     * @return array
     */
    public static function getWorkHour(){
        return [
            '07:00','08:00','09:00','10:00','11:00','12:00','13:00','14:00','15:00','16:00','17:00'
        ];
    }






    /**
     * 获取活动列表
     * @param $uid 可选
     * @param $page 页码
     * @param $pageSize 每页记录数
     * @param int $channel 频道
     * @param $clientShow 展示渠道
     * @param int $type
     * @param int $eid
     * @param null $keyword
     * @return array
     * Author: Ricksun
     */
    public static function getOnlineList($page,$pageSize){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');


        $where = " status=1 AND beginShowTime < ".time();


        $eventsM=self::getItemInstance();

        
        $dataSuccess['total'] = $eventsM->where($where)->count();//获取数据总条数
        $dataSuccess['page'] = max($page,1);//返回当前页
        $dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
        $dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
        $offset = ($dataSuccess['page']-1)*$pageSize;
        $order = "showOrder DESC,id DESC";



        $list = $eventsM->where($where)
             ->field('id,title,imgList,brief,tag')
             ->limit($offset,$pageSize)
             ->order($order)
             ->select();

        foreach ($list as $k=>$one){
            $tags=explode(',',$one['tag']);
            $ar=array_rand($tags,2);
            $list[$k]['tag']=[];
            foreach ($ar as $ix){
                $list[$k]['tag'][]=$tags[$ix];
            }
        }
        
        $dataSuccess['data'] = $list;
        return $dataSuccess;
    }


    public static function getOrderList($uid,$page,$pageSize){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        if( !$uid ){
            $dataFailure['msg']='请指定用户';
            return $dataFailure;
        }


        $orderM = self::getOrderInstance();
        $where = " uid = {$uid}";


        $dataSuccess['total'] = $orderM->where($where)->count();//获取数据总条数
        $dataSuccess['page'] = $page ? $page : 1;//返回当前页
        $dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
        $dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
        $offset = ($dataSuccess['page']-1)*$pageSize;
        $list = $orderM->where($where)
            ->field('id,itemName,itemId,price,orderTime,status,addTime,LENGTH(comment) as hasComment')
            ->limit($offset,$pageSize)
            ->order(" id DESC ")->select();

        if($list){
            $orderStatusKv=self::getOrderStatusKv();
            $itemPicKv=self::getItemPicKv();
            foreach ($list as $key => $val){
                $list[$key]['statusName']   = isset($orderStatusKv[$val['status']])?$orderStatusKv[$val['status']]:'';
                $list[$key]['pic']          = isset($itemPicKv[$val['itemId']])?$itemPicKv[$val['itemId']]:'';
                $list[$key]['addTime']      = date('Y-m-d H:i:s',$val['addTime']);
            }
        }
        $dataSuccess['data'] = $list;
        return $dataSuccess;
    }


    /**
     * 新订单通知管理员
     * @param $orderId 订单号
     * @param $itemName 服务内容
     * @param $price 金额
     * @param null $openID
     */
    public static function sendTemplateMsg($orderId,$itemName,$price,$openID=null){
        if (is_null($openID)){
            $openID = DEFAULT_ANSWER_OPENID;//'o9VjL1IeF2CLYVgy8GPX8iWJWZqI';
        }
        $templateId=WECHAT_TEMPLATE_HOUSEWORK;//'zT3H9O8Y7_8t37MecHyvNsATVgzFn9Zk-u5ji6EWPCE';
        $url=u('PointMall/info?id='.$orderId);
        $templateMsg=array(
            'touser'=>$openID,
            'template_id'=>$templateId,
            'url'=>$url,
            "topcolor"=>"#FF0000",
            'data'=>array(
                "first"=>array(
                    "value"=>"家政服务有新订单生成，请及时处理",
                    "color"=>"#173177"
                ),
                "keyword1"=>array(
                    "value"=>$orderId,
                    "color"=>"#173177"
                ),
                "keyword2"=>array(
                    "value"=>$itemName,
                    "color"=>"#173177"
                ),
                "keyword3"=>array(
                    "value"=>$price,
                    "color"=>"#173177"
                ),
                "keyword4"=>array(
                    "value"=>'等待处理',
                    "color"=>"#173177"
                ),
                "keyword5"=>array(
                    "value"=>date('Y-m-d H:i:s',time()),
                    "color"=>"#173177"
                ),
                "remark"=>array(
                    "value"=>"请尽快登陆后台进行回复",
                    "color"=>"#173177"
                ),
            )
        );
        $content=json_encode($templateMsg);
        WeixinModel::sendTemplateMsg($content);
    }
}